import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  NavBar,
  Form,
  Input,
  Button,
  ImageUploader,
  Toast,
  Dialog,
  Avatar
} from 'antd-mobile';
import { getUserAvatarPlaceholder } from '../../utils/imageUtils';
import './Account.css';

const Account = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [userInfo, setUserInfo] = useState(null);
  const [fileList, setFileList] = useState([]);
  const [loading, setLoading] = useState(false);

  // 加载用户信息
  useEffect(() => {
    const storedUserInfo = localStorage.getItem('userInfo');
    if (!storedUserInfo) {
      navigate('/login');
      return;
    }

    const parsedUserInfo = JSON.parse(storedUserInfo);
    setUserInfo(parsedUserInfo);

    // 设置表单初始值
    form.setFieldsValue({
      username: parsedUserInfo.username,
      email: parsedUserInfo.email || '',
      phone: parsedUserInfo.phone || '',
      nickname: parsedUserInfo.nickname || '',
    });

    // 如果有头像，设置到文件列表
    if (parsedUserInfo.avatar) {
      setFileList([{ url: parsedUserInfo.avatar }]);
    }
  }, [navigate, form]);

  // 返回上一页
  const back = () => {
    navigate(-1);
  };

  // 处理头像上传
  const handleUpload = async (file) => {
    // 这里模拟上传，实际项目中应该调用上传接口
    return new Promise((resolve) => {
      // 使用FileReader读取文件内容
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        // 返回base64格式的图片数据作为URL
        resolve({ url: reader.result });
      };
    });
  };

  // 提交表单
  const onFinish = (values) => {
    setLoading(true);

    // 模拟API请求
    setTimeout(() => {
      const updatedUserInfo = {
        ...userInfo,
        ...values,
        avatar: fileList.length > 0 ? fileList[0].url : null,
      };

      // 保存到本地存储
      localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo));
      setUserInfo(updatedUserInfo);

      Toast.show({
        icon: 'success',
        content: '保存成功',
      });

      setLoading(false);
    }, 1000);
  };

  // 确认放弃修改
  const confirmCancel = () => {
    Dialog.confirm({
      content: '确定放弃修改吗？',
      onConfirm: () => {
        navigate(-1);
      },
    });
  };

  if (!userInfo) {
    return (
      <div className="loading-container">
        <div className="loading-spinner">加载中...</div>
      </div>
    );
  }

  return (
    <div className="account-page">
      <NavBar onBack={back}>个人信息</NavBar>

      <div className="account-container">
        <div className="avatar-container">
          <Avatar
            src={userInfo.avatar || getUserAvatarPlaceholder(userInfo.username, '128x128')}
            style={{ '--size': '80px' }}
          />
        </div>

        <Form
          form={form}
          layout="horizontal"
          onFinish={onFinish}
          footer={
            <div className="form-buttons">
              <Button block color="default" onClick={confirmCancel}>
                取消
              </Button>
              <Button block type="submit" color="primary" loading={loading}>
                保存
              </Button>
            </div>
          }
        >
          <Form.Header>基本信息</Form.Header>
          
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>
          
          <Form.Item
            name="nickname"
            label="昵称"
          >
            <Input placeholder="请输入昵称" />
          </Form.Item>
          
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { 
                type: 'email',
                message: '请输入有效的邮箱地址'
              }
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          
          <Form.Item
            name="phone"
            label="手机号"
            rules={[
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '请输入有效的手机号'
              }
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>
          
          <Form.Header>头像</Form.Header>
          
          <Form.Item name="avatar" label="上传头像">
            <ImageUploader
              value={fileList}
              onChange={setFileList}
              upload={handleUpload}
              maxCount={1}
              showUpload={fileList.length < 1}
            />
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Account; 